package com.bkaka.controller;

import com.bkaka.bean.ResponseBean;
import com.bkaka.dao.ExamUserDao;
import com.bkaka.entity.*;
import com.bkaka.service.*;
import org.omg.Messaging.SYNC_WITH_TRANSPORT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;

/**
 * Created by maxiaoqiang on 2018/9/3.
 */
@RestController
@RequestMapping(value = "${api.path}/paper")
public class ExamPaperController {

    @Value("${radio.count}")
    private Integer radioCount;

    @Value("${radio.score}")
    private String radioScore;

    @Value("${multi.count}")
    private Integer multiCount;

    @Value("${multi.score}")
    private String multiScore;

    @Value("${verdict.count}")
    private Integer verdictCount;

    @Value("${verdict.score}")
    private String verdictScore;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private ExamPaperServer service;

    @Autowired
    private ExamUserDao userDao;

    @Autowired
    private ExamSubjectService subjectService;

    @Autowired
    private ExamChapterService chapterService;

    @Autowired
    private ExamQuestionService questionService;

    @Autowired
    private ExamAnswerHistoryServer examAnswerHistoryServer;

    @GetMapping(value = "/list")
    public ResponseBean list(Integer userId) {
        List<ExamPaper> list = service.list(userId);
        List lists = new ArrayList();
        for (ExamPaper paper : list) {
            Double score = 0.0;
            List<ExamAnswerHistory> histroies = examAnswerHistoryServer.findByPaperId(paper.getId());
            for (ExamAnswerHistory history : histroies) {
                score += history.getUserScore();
            }
            Map map = new HashMap();
            map.put("paper", paper);
            map.put("score", score);
            lists.add(map);
        }
        return new ResponseBean(200, "SUCCESS", lists);
    }

    @GetMapping(value = "/grade")
    public ResponseBean grade(Integer userId) {
        List<ExamPaper> list = service.grade(userId);
        List lists = new ArrayList();
        for (int i = 0; i<list.size();i++) {
            ExamPaper paper = list.get(i);
            Double score = 0.0;
            List<ExamAnswerHistory> histroies = examAnswerHistoryServer.findByPaperId(paper.getId());
            for (ExamAnswerHistory history : histroies) {
                score += history.getUserScore();
            }
            Map map = new HashMap();
            map.put("paper", paper);
            map.put("score", score);
            lists.add(map);
        }
        return new ResponseBean(200, "SUCCESS", lists);
    }


    @GetMapping(value = "/findAll", produces = "application/json;charset=UTF-8")
    public ResponseBean findAll(Integer userId, Integer paperId, Integer subjectId) {
        List<ExamPaper> list = service.findAll(userId, paperId, subjectId);
        List<Double> chapterScore = new ArrayList<>();
        List<Double> userScore = new ArrayList<>();
        for (ExamPaper paper : list) {
            for (ExamChapter chapter : paper.getChapterList()) {
                List<ExamAnswerHistory> examAnswerHistories = examAnswerHistoryServer.countScore(chapter.getId(), paperId);
                Double score1 = 0.0;
                Double score2 = 0.0;
                // 统计每章章节的分数和自己所得的分数
                for (ExamAnswerHistory history : examAnswerHistories) {
                    score1 += Double.parseDouble(history.getQuestionScore().split("/")[1]);
                    score2 += history.getUserScore();
                }
                chapterScore.add(score1);
                userScore.add(score2);
            }
        }
        Map map = new HashMap();
        map.put("list", list.get(0));
        map.put("chapterScore", chapterScore);
        map.put("userScore", userScore);
        return new ResponseBean(200, "SUCCESS", map);
    }

    @GetMapping(value = "/begin", produces = "application/json;charset=UTF-8")
    public ResponseBean begin(Integer paperId){
        Integer userId = Integer.parseInt(request.getHeader("userId"));
        ExamUser user = userDao.findById(userId);
        if(user.getIdCard()==null && user.getName()==null){
            return new ResponseBean(500, "请前往个人中心，完善个人信息", null);
        }else{
            Long nowTime = new Date().getTime()/1000;
            ExamPaper paper = service.findById(paperId);
            if(paper.getStartTime()>nowTime){
                return new ResponseBean(500, "还未到开始时间，请耐心等待哦！", null);
            }else{
                return new ResponseBean(200, "success", null);
            }
        }
    }

    @GetMapping(value = "/count", produces = "application/json;charset=UTF-8")
    public ResponseBean count(Integer userId){
        List<ExamPaper> paper = service.countInit(userId);
        return new ResponseBean(200, "success", paper);

    }

    @ResponseBody
    @PostMapping(value = "/create/{userId}", produces = "application/json;charset=UTF-8")
    public ResponseBean create(@PathVariable Integer userId, @Valid @RequestBody ExamPaper paper) {

        // 设置单选
        if (paper.getRadio() != null) {
            radioCount = paper.getRadio();
        } else {
            paper.setRadio(radioCount);
        }
        if (paper.getRadioValue() != "") {
            radioScore = paper.getRadioValue();
        } else {
            paper.setRadioValue(radioScore);
        }

        // 设置多选
        if (paper.getMulti() != null) {
            multiCount = paper.getMulti();
        } else {
            paper.setMulti(multiCount);
        }
        if (paper.getMultiValue() != "") {
            multiScore = paper.getMultiValue();
        } else {
            paper.setMultiValue(multiScore);
        }

        // 设置判断题
        if (paper.getVerdict() != null) {
            verdictCount = paper.getVerdict();
        } else {
            paper.setVerdict(verdictCount);
        }
        if (paper.getVerdictValue() != "") {
            verdictScore = paper.getVerdictValue();
        } else {
            paper.setMultiValue(verdictScore);
        }

        Double score = radioCount * Double.parseDouble(radioScore.split("/")[1]) + multiCount * Double.parseDouble(multiScore.split("/")[1]) + verdictCount * Double.parseDouble(verdictScore.split("/")[1]);

        ExamSubject subject = subjectService.findById(paper.getSubjectId());
        // 创建试卷
        paper.setTotal(score);
        paper.setName(subject.getName());
        paper.setCreateTime(new Date().getTime());
        paper.setUserId(userId);
        service.create(paper);

        // 根据试卷规则和分配比重生成试卷题目记录
        int level = paper.getLevel();
        //试题等级 setUpQuestion(课程ID, 难度等级, 单选个数, 多选个数, 判断个数)
        List<ExamQuestion> questionList = setUpQuestion(paper.getSubjectId(), level, radioCount, multiCount, verdictCount);
        for (ExamQuestion question : questionList) {
            ExamAnswerHistory history = new ExamAnswerHistory();
            history.setExamPaperId(paper.getId());
            history.setExamQuestionId(question.getId());
            history.setExamAnswer(question.getAnswer());
            history.setUserId(userId);
            String questionScore = "";
            if (question.getType() == 0) {
                questionScore = radioScore;
            } else if (question.getType() == 1) {
                questionScore = multiScore;
            } else if (question.getType() == 2) {
                questionScore = verdictScore;
            }
            history.setQuestionScore(questionScore);
            examAnswerHistoryServer.create(history);
        }
        return new ResponseBean(200, "SUCCESS", paper);
    }

    @ResponseBody
    @PostMapping(value = "/update", produces = "application/json;charset=UTF-8")
    public ResponseBean update(@Valid @RequestBody ExamPaper paper) {
        service.update(paper);
        return new ResponseBean(200, "SUCCESS", paper);
    }

    // 生成试题规则
    private List<ExamQuestion> setUpQuestion(Integer subjectId, Integer level, Integer radioCount, Integer multiCount, Integer verdictCount) {
        // 根据课程ID 回去所有单选题
        List<ExamChapter> chapterList = chapterService.findByChapter(subjectId);

        List<ExamQuestion> questionList = new ArrayList();
        Integer radioSize = 0;
        Integer multiSize = 0;
        Integer verdictSize = 0;

        for (ExamChapter chapter : chapterList) {
            int limit = 0;
            int percent = chapter.getpercent();

            // 根据课程ID 等级  获取单选题
            limit = (int) Math.floor(percent * radioCount / 100);
            limit = limit>=1?limit-1:limit;
            List<ExamQuestion> radioList = questionService.findByRule(chapter.getExamSubjectId(), chapter.getId(), 0, level, limit);
            for (ExamQuestion question : radioList) {
                questionList.add(question);
            }
            radioSize += radioList.size();

            // 根据课程ID 等级  获取多选题
            limit = (int) Math.floor(percent * multiCount / 100);
            limit = limit>=1?limit-1:limit;
            List<ExamQuestion> multiList = questionService.findByRule(chapter.getExamSubjectId(), chapter.getId(), 1, level, limit);
            for (ExamQuestion question : multiList) {
                questionList.add(question);
            }
            multiSize += multiList.size();

            // 根据课程ID 等级  获取判断题
            limit = (int) Math.floor(percent * verdictCount / 100);
            limit = limit>=1?limit-1:limit;
            List<ExamQuestion> verdictList = questionService.findByRule(chapter.getExamSubjectId(), chapter.getId(), 2, level, limit);
            for (ExamQuestion question : verdictList) {
                questionList.add(question);
            }
            verdictSize += verdictList.size();
        }

        // 根据比重生成试卷之后 如果题目个数对不上则随机选取 补齐
        if (radioSize < radioCount) {
            List<ExamQuestion> radioList = questionService.findByRule(subjectId, null, null, -1, radioCount - radioSize);
            for (ExamQuestion question : radioList) {
                questionList.add(question);
            }
        }
        if (multiSize < multiCount) {
            List<ExamQuestion> multiList = questionService.findByRule(subjectId, null, null, -1, multiCount - multiSize);
            for (ExamQuestion question : multiList) {
                questionList.add(question);
            }
        }
        if (verdictSize < verdictCount) {
            List<ExamQuestion> verdictList = questionService.findByRule(subjectId, null, null, -1, verdictCount - verdictSize);
            for (ExamQuestion question : verdictList) {
                questionList.add(question);
            }
        }
        return questionList;
    }

}
